package com.cmpe.av.androidservice;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cmpe.av.logic.UserLogic;
import com.cmpe.av.model.User;

/**
 * Servlet implementation class AndroidRegister
 */
@WebServlet("/AndroidRegister")
public class AndroidRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AndroidRegister() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserLogic msAccess;
		User user = new User();
		String name = request.getParameter("name");
		String surname = request.getParameter("surname");
		String userName = request.getParameter("username");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		boolean nameExist;
		try {
			msAccess = new UserLogic();
			nameExist = msAccess.isInDb(userName);
			if(nameExist)
			{
				response.getWriter().print("User already exists");
				return;
			}
			user.setName(name);
			user.setSurname(surname);
			user.setUsername(userName);
			user.setEmail(email);
			user.setPassword(password);
			user.setIsAdmin(0);
			msAccess.addUser(user);

		}catch (Exception e) {
			e.printStackTrace();
			response.getWriter().print("User already exists");
			return;
		}
		response.getWriter().print("success");


	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}


	public static boolean checkEmail(String email){
		int atPosition;
		atPosition=email.indexOf('@');
		if(atPosition==-1)
			return false;
		int nt;
		nt=email.lastIndexOf('.');
		if(nt<atPosition)
			return false;
		if(nt==email.length()-1)
			return false;
		return true;
	}

}
